package com.woniuxy.controller;

import com.woniuxy.model.entity.TransactionOrder;
import com.woniuxy.service.TransactionOrderService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api(tags = "交易订单管理")
@Slf4j
@RestController
@RequestMapping("/transaction")
public class TransactionOrderController {

    @Autowired
    private TransactionOrderService transactionOrderService;

    /**
     * 根据订单号查询交易订单详情
     */
    @GetMapping("/tDetails/{orderNo}")
    public ResponseEntity<?> getTransactionDetails(@PathVariable String orderNo) {
        try {
            TransactionOrder transactionOrder = transactionOrderService.getTransactionByOrderNo(orderNo);
            if (transactionOrder == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("订单不存在");
            }
            return ResponseEntity.ok(transactionOrder);
        } catch (Exception e) {
            log.error("获取交易详情失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取交易详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建交易订单
     */
    @PostMapping("/create")
    public ResponseEntity<?> createTransactionOrder(@RequestBody TransactionOrder transactionOrder) {
        try {
            transactionOrderService.createTransactionOrder(transactionOrder);
            return ResponseEntity.ok("交易订单创建成功");
        } catch (Exception e) {
            log.error("创建交易订单失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("创建交易订单失败：" + e.getMessage());
        }
    }

    /**
     * 更新交易订单状态
     */
    @PostMapping("/updateStatus")
    public ResponseEntity<?> updateTransactionStatus(@RequestBody Map<String, Object> payload) {
        try {
            String orderNo = (String) payload.get("orderNo");
            Integer status = (Integer) payload.get("status");
            Integer paymentStatus = (Integer) payload.get("paymentStatus"); // 新增付款状态字段

            transactionOrderService.updateTransactionStatus(orderNo, status, paymentStatus);
            return ResponseEntity.ok("交易订单状态更新成功");
        } catch (Exception e) {
            log.error("更新交易订单状态失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新交易订单状态失败：" + e.getMessage());
        }
    }

    /**
     * 支付交易订单
     *
     * @param orderNo 订单号
     * @param paymentRequest 支付方式请求
     * @return 支付结果
     */
    @PostMapping("/pay/{orderNo}")
    public ResponseEntity<?> payOrder(@PathVariable String orderNo, @RequestBody Map<String, Object> paymentRequest) {
        try {
            // 获取支付方式 ID
            Long paymentMethodId = ((Number) paymentRequest.get("paymentMethodId")).longValue();
            if (paymentMethodId == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("支付方式不能为空");
            }

            // 调用服务层处理支付逻辑
            boolean success = transactionOrderService.payOrder(orderNo, paymentMethodId);

            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("message", "支付成功");
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("支付失败");
            }
        } catch (RuntimeException e) {
            log.error("支付失败", e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (Exception e) {
            log.error("支付失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("支付失败：" + e.getMessage());
        }
    }

    @GetMapping("/pending")
    public ResponseEntity<?> getPendingPaymentOrders(@RequestParam Long customerId) {
        try {
            List<Map<String, Object>> orders = transactionOrderService.getPendingPaymentOrders(customerId);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            log.error("获取待付款订单失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取待付款订单失败：" + e.getMessage());
        }
    }

    @GetMapping("/completed")
    public ResponseEntity<?> getCompletedOrders(@RequestParam Long customerId) {
        try {
            List<Map<String, Object>> completedOrders = transactionOrderService.getCompletedOrders(customerId);
            return ResponseEntity.ok(completedOrders);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取已付款订单失败：" + e.getMessage());
        }
    }

    @GetMapping("/details/{orderNumber}")
    public ResponseEntity<?> getOrderDetails(@PathVariable String orderNumber) {
        try {
            Map<String, Object> orderDetails = transactionOrderService.getOrderDetails(orderNumber);
            return ResponseEntity.ok(orderDetails);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取订单详情失败：" + e.getMessage());
        }
    }

    @PostMapping("/refund")
    public ResponseEntity<?> refundOrder(@RequestBody Map<String, String> request) {
        String orderNumber = request.get("orderNumber");
        boolean success = transactionOrderService.refundOrder(orderNumber);
        if (success) {
            return ResponseEntity.ok(Collections.singletonMap("success", true));
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Collections.singletonMap("success", false));
        }
    }


}
